package com.hylanda.sys.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.hylanda.sys.dao.RoleRepository;
import com.hylanda.sys.entity.UPermission;
import com.hylanda.sys.entity.URole;
import com.hylanda.sys.model.URoleQo;

@Service
public class RoleService {
    @Autowired
    private RoleRepository roleRepository;

    public URole findById(Long id) {
        URole uRole = roleRepository.findOne(id);
        return uRole;
    }

    public URole create(URole uRole) {
        URole newURole = roleRepository.save(uRole);
        return newURole;
    }

    public URole update(URole uRole) {
        return roleRepository.save(uRole);
    }

    public void delete(Long id) {
    	roleRepository.delete(id);
    }

    public Page<URole> findPage(URoleQo uRoleQo){
       Pageable pageable = new PageRequest(uRoleQo.getPage(), uRoleQo.getSize(), new Sort(Sort.Direction.ASC, "id"));
       return roleRepository.findAll(pageable);
    }

	public List<UPermission> findByRoleIds(List<URole> roleList) {
		List<Long> ids =new ArrayList<>();
		for(URole role:roleList){
			ids.add(role.getId());
		}
		List<URole> roles= roleRepository.findAll(ids);
		List<UPermission> permissions=new ArrayList<UPermission>();
		for(URole r:roles){
			permissions.addAll(r.getPermissions());
		}
		return permissions;
	}

	public List<URole> findAll() {
		 List<URole> deparments =roleRepository.findAll();
	     return deparments;
	}

}
